package com.gcl.rabbirmq;

import com.gcl.rabbirmq.utils.RabbitMQUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class Consumer01 {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取信道
        Channel channel = RabbitMQUtils.getChannel();
        // 指定交换机
        channel.exchangeDeclare("normal_exchange", BuiltinExchangeType.DIRECT);
        // 死信交换机
        channel.exchangeDeclare("dead_exchange", BuiltinExchangeType.DIRECT);

        // 设置死信得具体参数
        Map<String, Object> parms = new HashMap<>();
        // 设置死信
        parms.put("x-dead-letter-exchange", "dead_exchange");
        parms.put("x-dead-letter-routing-key", "lisi");
        // 设置队列的最大长度( 10个会放到死信队列4个， 然后过10秒都放到死信中，超时了)
        parms.put("x-max-length", 6);

        // 声明队列
        channel.queueDeclare("normal_queue",false,false,false,parms);

        // 死信队列
        channel.queueDeclare("dead_queue",false,false,false,null);



        // 队列绑定交换器
        channel.queueBind("normal_queue", "normal_exchange", "zhangsan");

        channel.queueBind("dead_queue", "dead_exchange", "lisi");

        // 回调参数
        DeliverCallback deliverCallback = (a, b) -> {

            String msg = new String(b.getBody());
            if (msg.equals("info1")){
                channel.basicReject(b.getEnvelope().getDeliveryTag(), false);
            }else{

                System.out.println("打印正常的消息 "+ new String(b.getBody()));

                channel.basicAck(b.getEnvelope().getDeliveryTag(), false);
            }
        };

        CancelCallback cancelCallback = (a) -> {};

        // 消费消息
        channel.basicConsume("normal_queue", false,deliverCallback, cancelCallback);


    }

}
